{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "21fe0735",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "#  23\\.  使用交叉验证快速选择模型  # \n",
    "\n",
    "##  23.1.  介绍  # \n",
    "\n",
    "前面的课程中，我们一起学习了多个不同的分类预测方法。当你在实际工程实践时，如何快速地从这些机器学习方法中找到最适合的那一个呢？这就涉及到模型选择的知识。本次挑战中，我们将了解到 K 折交叉验证方法，并使用该方法完成模型选择。 \n",
    "\n",
    "##  23.2.  知识点  # \n",
    "\n",
    "  * K 折交叉验证 \n",
    "\n",
    "  * K 折子集均分 \n",
    "\n",
    "  * 鲍鱼年龄分类 \n",
    "\n",
    "我们学习了监督学习中的多个不同的分类方法，相信你已经对这些方法的原理和实现过程有了充分掌握。当你学完这些方法后，可能会产生一个疑问，那就是如何快速从不同的机器学习方法中挑选出最适合当前应用场景的方法呢？ \n",
    "\n",
    "要回答这个问题，我们先回顾一下 K-近邻方法 的实验内容。在 K-近邻课程的最后，实验介绍了 K 值的选择。当时，我们通过尝试从 2 到 10 的不同 K 值找到最适合的那一个。这个办法虽然看起来有点「笨」，但用起来还不错。 \n",
    "\n",
    "模型选择过程有点类似。当我们要从多个模型中快速选择一个较为合适的模型时，也可以把数据依次放到每个模型中去测试，找到泛化能力较强的那一个。虽然这是一个「笨」办法，但在实验流程上也有一些取巧的步骤。其中之一，就是今天要介绍的 K 折交叉验证。 \n",
    "\n",
    "关于交叉验证，实际上前面已经有所接触，这里就不再重复介绍概念了。 \n",
    "\n",
    "##  23.3.  数据集预处理  # \n",
    "\n",
    "下面正式开始本次挑战。本次挑战所使用到的是 Abalone（鲍鱼）年龄数据集 ` challenge-6-abalone.csv  ` 。首先，实验需要通过下面的链接下载该数据集。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "eb133b43",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "File 'challenge-6-abalone.csv' already there; not retrieving.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 数据集下载链接\n",
    "!wget -nc https://cdn.aibydoing.com/aibydoing/files/challenge-6-abalone.csv"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e402498",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "Exercise 23.1 \n",
    "\n",
    "挑战：加载并预览数据集前 5 行。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "e298f71e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "## 代码开始 ### (≈ 2 行代码)\n",
    "df = None\n",
    "## 代码结束 ###"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f02063b",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "参考答案  Exercise 23.1 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "2e14eeeb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>M</th>\n",
       "      <th>0.455</th>\n",
       "      <th>0.365</th>\n",
       "      <th>0.095</th>\n",
       "      <th>0.514</th>\n",
       "      <th>0.2245</th>\n",
       "      <th>0.101</th>\n",
       "      <th>0.15</th>\n",
       "      <th>15</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>M</td>\n",
       "      <td>0.35</td>\n",
       "      <td>0.265</td>\n",
       "      <td>0.09</td>\n",
       "      <td>0.2255</td>\n",
       "      <td>0.0995</td>\n",
       "      <td>0.0485</td>\n",
       "      <td>0.07</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>F</td>\n",
       "      <td>0.53</td>\n",
       "      <td>0.42</td>\n",
       "      <td>0.135</td>\n",
       "      <td>0.677</td>\n",
       "      <td>0.2565</td>\n",
       "      <td>0.1415</td>\n",
       "      <td>0.21</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>M</td>\n",
       "      <td>0.44</td>\n",
       "      <td>0.365</td>\n",
       "      <td>0.125</td>\n",
       "      <td>0.516</td>\n",
       "      <td>0.2155</td>\n",
       "      <td>0.114</td>\n",
       "      <td>0.155</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>I</td>\n",
       "      <td>0.33</td>\n",
       "      <td>0.255</td>\n",
       "      <td>0.08</td>\n",
       "      <td>0.205</td>\n",
       "      <td>0.0895</td>\n",
       "      <td>0.0395</td>\n",
       "      <td>0.055</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>I</td>\n",
       "      <td>0.425</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.095</td>\n",
       "      <td>0.3515</td>\n",
       "      <td>0.141</td>\n",
       "      <td>0.0775</td>\n",
       "      <td>0.12</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   M  0.455  0.365  0.095   0.514  0.2245   0.101   0.15  15\n",
       "0  M   0.35  0.265   0.09  0.2255  0.0995  0.0485   0.07   7\n",
       "1  F   0.53   0.42  0.135   0.677  0.2565  0.1415   0.21   9\n",
       "2  M   0.44  0.365  0.125   0.516  0.2155   0.114  0.155  10\n",
       "3  I   0.33  0.255   0.08   0.205  0.0895  0.0395  0.055   7\n",
       "4  I  0.425    0.3  0.095  0.3515   0.141  0.0775   0.12   8"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "### 代码开始 ### (≈ 2 行代码)\n",
    "df = pd.read_csv(\"challenge-6-abalone.csv\")\n",
    "df.head()\n",
    "### 代码结束 ###"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dbaad2bc",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "期望输出 \n",
    "\n",
    "|  M  |  0.455  |  0.365  |  0.095  |  0.514  |  0.2245  |  0.101  |  0.15  |  15   \n",
    "---|---|---|---|---|---|---|---|---|---  \n",
    "0  |  M  |  0.35  |  0.265  |  0.09  |  0.2255  |  0.0995  |  0.0485  |  0.07  |  7   \n",
    "1  |  F  |  0.53  |  0.42  |  0.135  |  0.677  |  0.2565  |  0.1415  |  0.21  |  9   \n",
    "2  |  M  |  0.44  |  0.365  |  0.125  |  0.516  |  0.2155  |  0.114  |  0.155  |  10   \n",
    "3  |  I  |  0.33  |  0.255  |  0.08  |  0.205  |  0.0895  |  0.0395  |  0.055  |  7   \n",
    "4  |  I  |  0.425  |  0.3  |  0.095  |  0.3515  |  0.141  |  0.0775  |  0.12  |  8   \n",
    "  \n",
    "此时，你会发现该数据集的列名有些问题，好像是数据值。其实，这是由于数据集不规范造成的，该数据集的列名位于最后一行，我们可以预览后 5 行查看。 \n",
    "\n",
    "Exercise 23.2 \n",
    "\n",
    "挑战：预览数据集最后 5 行。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "1bbd43f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 代码开始 ### (≈ 1 行代码)\n",
    "\n",
    "## 代码结束 ###"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45737507",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "参考答案  Exercise 23.2 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "6b50269d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>M</th>\n",
       "      <th>0.455</th>\n",
       "      <th>0.365</th>\n",
       "      <th>0.095</th>\n",
       "      <th>0.514</th>\n",
       "      <th>0.2245</th>\n",
       "      <th>0.101</th>\n",
       "      <th>0.15</th>\n",
       "      <th>15</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>4172</th>\n",
       "      <td>M</td>\n",
       "      <td>0.59</td>\n",
       "      <td>0.44</td>\n",
       "      <td>0.135</td>\n",
       "      <td>0.966</td>\n",
       "      <td>0.439</td>\n",
       "      <td>0.2145</td>\n",
       "      <td>0.2605</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4173</th>\n",
       "      <td>M</td>\n",
       "      <td>0.6</td>\n",
       "      <td>0.475</td>\n",
       "      <td>0.205</td>\n",
       "      <td>1.176</td>\n",
       "      <td>0.5255</td>\n",
       "      <td>0.2875</td>\n",
       "      <td>0.308</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4174</th>\n",
       "      <td>F</td>\n",
       "      <td>0.625</td>\n",
       "      <td>0.485</td>\n",
       "      <td>0.15</td>\n",
       "      <td>1.0945</td>\n",
       "      <td>0.531</td>\n",
       "      <td>0.261</td>\n",
       "      <td>0.296</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4175</th>\n",
       "      <td>M</td>\n",
       "      <td>0.71</td>\n",
       "      <td>0.555</td>\n",
       "      <td>0.195</td>\n",
       "      <td>1.9485</td>\n",
       "      <td>0.9455</td>\n",
       "      <td>0.3765</td>\n",
       "      <td>0.495</td>\n",
       "      <td>12</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4176</th>\n",
       "      <td>Sex</td>\n",
       "      <td>Length</td>\n",
       "      <td>Diameter</td>\n",
       "      <td>Height</td>\n",
       "      <td>Whole weight</td>\n",
       "      <td>Shucked weight</td>\n",
       "      <td>Viscera weight</td>\n",
       "      <td>Shell weight</td>\n",
       "      <td>Rings</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        M   0.455     0.365   0.095         0.514          0.2245  \\\n",
       "4172    M    0.59      0.44   0.135         0.966           0.439   \n",
       "4173    M     0.6     0.475   0.205         1.176          0.5255   \n",
       "4174    F   0.625     0.485    0.15        1.0945           0.531   \n",
       "4175    M    0.71     0.555   0.195        1.9485          0.9455   \n",
       "4176  Sex  Length  Diameter  Height  Whole weight  Shucked weight   \n",
       "\n",
       "               0.101          0.15     15  \n",
       "4172          0.2145        0.2605     10  \n",
       "4173          0.2875         0.308      9  \n",
       "4174           0.261         0.296     10  \n",
       "4175          0.3765         0.495     12  \n",
       "4176  Viscera weight  Shell weight  Rings  "
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 代码开始 ### (≈ 1 行代码)\n",
    "df.tail()\n",
    "### 代码结束 ###"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a60749e1",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "期望输出 \n",
    "\n",
    "|  M  |  0.455  |  0.365  |  0.095  |  0.514  |  0.2245  |  0.101  |  0.15  |  15   \n",
    "---|---|---|---|---|---|---|---|---|---  \n",
    "4172  |  M  |  0.59  |  0.44  |  0.135  |  0.966  |  0.439  |  0.2145  |  0.2605  |  10   \n",
    "4173  |  M  |  0.6  |  0.475  |  0.205  |  1.176  |  0.5255  |  0.2875  |  0.308  |  9   \n",
    "4174  |  F  |  0.625  |  0.485  |  0.15  |  1.0945  |  0.531  |  0.261  |  0.296  |  10   \n",
    "4175  |  M  |  0.71  |  0.555  |  0.195  |  1.9485  |  0.9455  |  0.3765  |  0.495  |  12   \n",
    "4176  |  Sex  |  Length  |  Diameter  |  Height  |  Whole weight  |  Shucked weight  |  Viscera weight  |  Shell weight  |  Rings   \n",
    "  \n",
    "如上表所示，索引为 4176 的行竟然是列名。所以，我们需要将列名放到正确的位置，也就是要重新生成数据集组成的 DataFrame。 \n",
    "\n",
    "Exercise 23.3 \n",
    "\n",
    "挑战：给数据集设定正确的列名，并保留被错误用于列名的数据行，同时删除最后一行被错误放置的列名。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "af896384",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 代码开始 ### (≈ 3～7 行代码)\n",
    "df = None\n",
    "## 代码结束 ###"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a34be3d5",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "参考答案  Exercise 23.3 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "25784c31",
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'NoneType' object has no attribute 'iloc'",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mAttributeError\u001b[39m                            Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[23]\u001b[39m\u001b[32m, line 2\u001b[39m\n\u001b[32m      1\u001b[39m \u001b[38;5;66;03m### 代码开始 ### (≈ 3～7 行代码)\u001b[39;00m\n\u001b[32m----> \u001b[39m\u001b[32m2\u001b[39m columns_name = \u001b[43mdf\u001b[49m\u001b[43m.\u001b[49m\u001b[43miloc\u001b[49m[df.index[-\u001b[32m1\u001b[39m]].values\n\u001b[32m      3\u001b[39m new_line = df.columns.values\n\u001b[32m      4\u001b[39m df = df.drop(df.index[-\u001b[32m1\u001b[39m])\n",
      "\u001b[31mAttributeError\u001b[39m: 'NoneType' object has no attribute 'iloc'"
     ]
    }
   ],
   "source": [
    "### 代码开始 ### (≈ 3～7 行代码)\n",
    "columns_name = df.iloc[df.index[-1]].values\n",
    "new_line = df.columns.values\n",
    "df = df.drop(df.index[-1])\n",
    "df.columns = columns_name\n",
    "df = pd.DataFrame([new_line], columns=columns_name).append(df, ignore_index=True)\n",
    "### 代码结束 ###\n",
    "\n",
    "### 方法二\n",
    "df = pd.read_csv(\"challenge-6-abalone.csv\", header=-1)\n",
    "df.columns = df.iloc[-1].values\n",
    "df = df.drop(df.index[-1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "960fb679",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "运行测试 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "47592eab",
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'NoneType' object has no attribute 'head'",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mAttributeError\u001b[39m                            Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[16]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m pd.concat([\u001b[43mdf\u001b[49m\u001b[43m.\u001b[49m\u001b[43mhead\u001b[49m(\u001b[32m2\u001b[39m), df.tail(\u001b[32m2\u001b[39m)])\n",
      "\u001b[31mAttributeError\u001b[39m: 'NoneType' object has no attribute 'head'"
     ]
    }
   ],
   "source": [
    "pd.concat([df.head(2), df.tail(2)])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dac4135e",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "期望输出 \n",
    "\n",
    "|  Sex  |  Length  |  Diameter  |  Height  |  Whole weight  |  Shucked weight  |  Viscera weight  |  Shell weight  |  Rings   \n",
    "---|---|---|---|---|---|---|---|---|---  \n",
    "0  |  M  |  0.455  |  0.365  |  0.095  |  0.514  |  0.2245  |  0.101  |  0.15  |  15   \n",
    "1  |  M  |  0.35  |  0.265  |  0.09  |  0.2255  |  0.0995  |  0.0485  |  0.07  |  7   \n",
    "4175  |  F  |  0.625  |  0.485  |  0.15  |  1.0945  |  0.531  |  0.261  |  0.296  |  10   \n",
    "4176  |  M  |  0.71  |  0.555  |  0.195  |  1.9485  |  0.9455  |  0.3765  |  0.495  |  12   \n",
    "  \n",
    "到目前为止，我们已经设定好了正确的数据集格式。该数据集前 8 列统计了鲍鱼的一些生理特征，例如性别、长度、重量等。最后 1 列为目标列，统计了鲍鱼的环数（Rings），环数从 1-30 变化，值越大代表鲍鱼的年龄越大。 \n",
    "\n",
    "你可能会意识到，如果我们要预测鲍鱼的年龄，那么这应该是一个回归问题。所以，本次实验将 1-10 环定义为 small（小鲍鱼）, 11-20 环定为 middle（中型鲍鱼）, 21-30 定为 large（老鲍鱼）。 \n",
    "\n",
    "于此同时，针对 Sex 列出现的 3 个性别种类 M, F, I，我们分别使用数值 0，1，2 进行替换。 \n",
    "\n",
    "Exercise 23.4 \n",
    "\n",
    "挑战：将数据集目标值（Rings）按照区间替换为 3 种类别，并按照上文要求替换 Sex 列。 \n",
    "\n",
    "提示：按区间替换是可使用 ` pd.cut()  ` ，具体参考官方文档。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2fc151d",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 代码开始 ### (≈ 3~5 行代码)\n",
    "\n",
    "## 代码结束 ###"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c161390",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "参考答案  Exercise 23.4 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "8206a7b0",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'NoneType' object is not subscriptable",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mTypeError\u001b[39m                                 Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[15]\u001b[39m\u001b[32m, line 2\u001b[39m\n\u001b[32m      1\u001b[39m \u001b[38;5;66;03m### 代码开始 ### (≈ 3~5 行代码)\u001b[39;00m\n\u001b[32m----> \u001b[39m\u001b[32m2\u001b[39m df[\u001b[33m'\u001b[39m\u001b[33mRings\u001b[39m\u001b[33m'\u001b[39m] = pd.to_numeric(\u001b[43mdf\u001b[49m\u001b[43m[\u001b[49m\u001b[33;43m'\u001b[39;49m\u001b[33;43mRings\u001b[39;49m\u001b[33;43m'\u001b[39;49m\u001b[43m]\u001b[49m)\n\u001b[32m      3\u001b[39m df[\u001b[33m'\u001b[39m\u001b[33mRings\u001b[39m\u001b[33m'\u001b[39m] = pd.cut(df.Rings, bins=[\u001b[32m0\u001b[39m, \u001b[32m10\u001b[39m, \u001b[32m20\u001b[39m, \u001b[32m30\u001b[39m], labels=[\u001b[33m'\u001b[39m\u001b[33msmall\u001b[39m\u001b[33m'\u001b[39m,\u001b[33m'\u001b[39m\u001b[33mmiddle\u001b[39m\u001b[33m'\u001b[39m,\u001b[33m'\u001b[39m\u001b[33mlarge\u001b[39m\u001b[33m'\u001b[39m])\n\u001b[32m      4\u001b[39m df[\u001b[33m'\u001b[39m\u001b[33mSex\u001b[39m\u001b[33m'\u001b[39m] = df.Sex.replace({\u001b[33m'\u001b[39m\u001b[33mM\u001b[39m\u001b[33m'\u001b[39m:\u001b[32m0\u001b[39m, \u001b[33m'\u001b[39m\u001b[33mF\u001b[39m\u001b[33m'\u001b[39m:\u001b[32m1\u001b[39m, \u001b[33m'\u001b[39m\u001b[33mI\u001b[39m\u001b[33m'\u001b[39m:\u001b[32m2\u001b[39m})\n",
      "\u001b[31mTypeError\u001b[39m: 'NoneType' object is not subscriptable"
     ]
    }
   ],
   "source": [
    "### 代码开始 ### (≈ 3~5 行代码)\n",
    "df['Rings'] = pd.to_numeric(df['Rings'])\n",
    "df['Rings'] = pd.cut(df.Rings, bins=[0, 10, 20, 30], labels=['small','middle','large'])\n",
    "df['Sex'] = df.Sex.replace({'M':0, 'F':1, 'I':2})\n",
    "### 代码结束 ###"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4be9172",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "运行测试 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "40b85e34",
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'NoneType' object has no attribute 'iloc'",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mAttributeError\u001b[39m                            Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[14]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[43mdf\u001b[49m\u001b[43m.\u001b[49m\u001b[43miloc\u001b[49m[[\u001b[32m3\u001b[39m, \u001b[32m6\u001b[39m, \u001b[32m12\u001b[39m, \u001b[32m83\u001b[39m]][\u001b[33m\"\u001b[39m\u001b[33mRings\u001b[39m\u001b[33m\"\u001b[39m].values)\n\u001b[32m      2\u001b[39m df.head()\n",
      "\u001b[31mAttributeError\u001b[39m: 'NoneType' object has no attribute 'iloc'"
     ]
    }
   ],
   "source": [
    "print(df.iloc[[3, 6, 12, 83]][\"Rings\"].values)\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "039021bd",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "期望输出 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f849ccc2",
   "metadata": {},
   "outputs": [],
   "source": [
    "[small, middle, middle, large]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "068c922e",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "|  Sex  |  Length  |  Diameter  |  Height  |  Whole weight  |  Shucked weight  |  Viscera weight  |  Shell weight  |  Rings   \n",
    "---|---|---|---|---|---|---|---|---|---  \n",
    "0  |  0  |  0.455  |  0.365  |  0.095  |  0.514  |  0.2245  |  0.101  |  0.15  |  middle   \n",
    "1  |  0  |  0.35  |  0.265  |  0.09  |  0.2255  |  0.0995  |  0.0485  |  0.07  |  small   \n",
    "2  |  1  |  0.53  |  0.42  |  0.135  |  0.677  |  0.2565  |  0.1415  |  0.21  |  small   \n",
    "3  |  0  |  0.44  |  0.365  |  0.125  |  0.516  |  0.2155  |  0.114  |  0.155  |  small   \n",
    "4  |  2  |  0.33  |  0.255  |  0.08  |  0.205  |  0.0895  |  0.0395  |  0.055  |  small   \n",
    "  \n",
    "##  23.4.  K 折子集均分  # \n",
    "\n",
    "接下来，我们将上面预处理之后的数据集平均划分为 K 个子集。这里，使用 scikit-learn 提供的 K 折划分方法如下： "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a18c2ca8",
   "metadata": {},
   "outputs": [],
   "source": [
    "sklearn.model_selection.KFold(n_splits=3, shuffle=False, random_state=None)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e79ba1b1",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "其中参数： "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "366f30c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "- n_splits : 默认 3；最小为 2，表示 K 折子集划分的 K 值。\n",
    "- shuffle : 默认 False; 当为 True 时，会对数据产生随机搅动。\n",
    "- random_state : 默认 None；随机数种子。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60138559",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "Exercise 23.5 \n",
    "\n",
    "挑战：使用 ` KFold()  ` 将数据集划分为 10 折，指定参数： ` shuffle=False  ` ， ` random_state=50  ` 。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b00a837e",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 代码开始 ### (≈ 2 行代码)\n",
    "kf = None\n",
    "## 代码结束 ###"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9a84602f",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "参考答案  Exercise 23.5 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95efd4be",
   "metadata": {},
   "outputs": [],
   "source": [
    "### 代码开始 ### (≈ 2 行代码)\n",
    "from sklearn.model_selection import KFold\n",
    "kf = KFold(n_splits=10, random_state=50)\n",
    "### 代码结束 ###"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01db493c",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "运行测试 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77c06dfa",
   "metadata": {},
   "outputs": [],
   "source": [
    "kf"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24f11d59",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "期望输出 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22215b5f",
   "metadata": {},
   "outputs": [],
   "source": [
    "KFold(n_splits=10, random_state=50, shuffle=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3ca921c",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "如果想要得到划分的结果，就可以通过 ` for  ` 循环完成： "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b82b4694",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 直接运行查看结果\n",
    "for train_index, test_index in kf.split(df):\n",
    "    print(\"TRAIN:\", len(train_index), \"TEST:\", len(test_index))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "937f496d",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "这里使用 ` len()  ` 打印了 ` train_index  ` 的长度，你也可以自行尝试打印 ` train_index  ` 中的内容。 \n",
    "\n",
    "##  23.5.  K 折交叉验证  # \n",
    "\n",
    "上面，我们使用 ` KFold()  ` 可以很方便地完成 K 折划分，你可以将划分的结果用于训练模型并验证。为了方便，scikit-learn 还提供了直接交叉验证的方法，可以大大缩减代码量： "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9389cfe",
   "metadata": {},
   "outputs": [],
   "source": [
    "sklearn.model_selection.cross_val_score(estimator, X, y=None, groups=None, scoring=None, cv=None, n_jobs=1, verbose=0, fit_params=None, pre_dispatch=‘2*n_jobs’)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d78e1391",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "主要参数： "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2d26ff25",
   "metadata": {},
   "outputs": [],
   "source": [
    "- estimator : 模型。\n",
    "- X : 特征组成的数组。\n",
    "- y : 目标值组成的数组。\n",
    "- cv : K 折数量。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c0731c7",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "Exercise 23.6 \n",
    "\n",
    "挑战：使用 K-近邻方法构建机器学习分类模型，并进行 10 折交叉验证。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3b262fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 代码开始 ### (≈ 4~7 行代码)\n",
    "cross_val_score()\n",
    "## 代码结束 ###"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7cf6a79",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "参考答案  Exercise 23.6 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c42ae23a",
   "metadata": {},
   "outputs": [],
   "source": [
    "### 代码开始 ### (≈ 4~7 行代码)\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "features = df.iloc[:, 0:8]\n",
    "target = df['Rings']\n",
    "\n",
    "model = KNeighborsClassifier()\n",
    "cross_val_score(model, X=features, y=target, cv=10)\n",
    "### 代码结束 ###"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d434a60a",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "期望输出 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1a1932f",
   "metadata": {},
   "outputs": [],
   "source": [
    "array([0.75417661, 0.72009569, 0.77990431, 0.72966507, 0.73205742,\n",
    "       0.74401914, 0.76498801, 0.74580336, 0.75779376, 0.73860911])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60917b22",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "由于 10 折交叉验证会进行 10 次实验，所以最终输出了 10 个分类准确率的评价结果。 \n",
    "\n",
    "如果我们要使用鲍鱼数据集训练分类预测模型，为了快速筛选出表现较好的模型，就可以使用 K 折交叉验证。所以，接下来我们将得到本章课程中所学习模型在默认参数下的 10 折交叉验证结果。 \n",
    "\n",
    "Exercise 23.7 \n",
    "\n",
    "挑战：使用 10 折交叉验证方法测试鲍鱼数据集在逻辑回归、K 近邻、支持向量机、人工神经网络、决策树、随机森林、Adaboost 默认参数下的表现结果，并取 10 折交叉验证结果取平均值。 \n",
    "\n",
    "提示：人工神经网络模型调用方法为： ` sklearn.neural_network.MLPClassifier  ` 。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "472f92bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"加载分类器模块\n",
    "\"\"\"\n",
    "## 代码开始 ### (≈ 7 行代码)\n",
    "\n",
    "## 代码结束 ###\n",
    "\n",
    "\"\"\"各分类模型 10 折交叉验证函数\n",
    "\"\"\"\n",
    "\n",
    "def classifiers():\n",
    "    \"\"\"\n",
    "    参数:无\n",
    "\n",
    "    返回:\n",
    "    scores -- 各分类模型 10 折交叉验证平均结果（列表）\n",
    "    \"\"\"\n",
    "    ### 代码开始 ### (> 10 行代码)\n",
    "    scores = []\n",
    "    ### 代码结束 ###\n",
    "\n",
    "    return scores"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff23b833",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "参考答案  Exercise 23.7 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7316351",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"加载分类器模块\n",
    "\"\"\"\n",
    "### 代码开始 ### (≈ 7 行代码)\n",
    "import numpy as np\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.svm import SVC\n",
    "from sklearn.neural_network import MLPClassifier\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.ensemble import AdaBoostClassifier\n",
    "\n",
    "### 代码结束 ###\n",
    "\n",
    "\"\"\"各分类模型 10 折交叉验证函数\n",
    "\"\"\"\n",
    "def classifiers():\n",
    "\n",
    "    \"\"\"\n",
    "    参数:无\n",
    "\n",
    "    返回:\n",
    "    scores -- 各分类模型 10 折交叉验证平均结果（列表）\n",
    "    \"\"\"\n",
    "    ### 代码开始 ### (> 10 行代码)\n",
    "    scores = []\n",
    "\n",
    "    models = [\n",
    "        LogisticRegression(),\n",
    "        KNeighborsClassifier(),\n",
    "        SVC(),\n",
    "        MLPClassifier(),\n",
    "        DecisionTreeClassifier(),\n",
    "        RandomForestClassifier(),\n",
    "        AdaBoostClassifier()]\n",
    "\n",
    "    for model in models:\n",
    "        score = cross_val_score(model, X=features, y=target, cv=10)\n",
    "        mean_score = np.mean(score)\n",
    "        scores.append(mean_score)\n",
    "    ### 代码结束 ###\n",
    "\n",
    "    return scores"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97268a91",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "运行测试（执行时间较长） "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dccb80bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "classifiers()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "033a8d51",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "参考输出： "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7bb3faec",
   "metadata": {},
   "outputs": [],
   "source": [
    "[0.7543513318292162,0.7467112482377095, 0.7443091754229052,0.7648902636235668,\n",
    " 0.6856593267369182,0.7455041701414079, 0.7318638234403398]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5097ecdb",
   "metadata": {},
   "source": [
    "* 上面的输出结果仅供参考，每次执行的结果可能会有所不同。 \n",
    "\n",
    "你会发现，当我们使用默认参数时，7 种分类预测模型的表现都还不错，其中支持向量机、人工神经网络、随机森林等表现突出。此时，我们就可以先初选出这几种方法，然后通过调参得到更理想的结果。 "
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  },
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
